from flask import Blueprint, request, jsonify
from app.Service.ThingService  import ThingService
from app.Utils.exceptions import BusinessException
from app.Utils.response import success, error
from app.db import db

thing_controller = Blueprint('thing_controller', __name__, url_prefix='/myapp/admin/thing')
service = ThingService(db)

@thing_controller.route('/list', methods=['GET'])
def list_things():
    """分页查询商品"""
    page = request.args.get('page', type=int, default=1)
    page_size = request.args.get('pageSize', type=int, default=10)
    result = service.list_things(page, page_size)
    return jsonify(success(result, "商品分页查询成功"))

@thing_controller.route('/delete', methods=['DELETE'])
def delete_things():
    """批量删除商品"""
    data = request.get_json()
    ids = data.get('ids', [])
    if not ids:
        return jsonify(error(400, "缺少必要参数: ids"))
    service.delete_things(ids)
    return jsonify(success(None, "商品批量删除成功"))

@thing_controller.route('/update', methods=['POST'])
def update_thing():
    """更新商品信息"""
    data = request.get_json()
    try:
        result = service.update_thing(data)
        return jsonify(success(result, "商品修改成功"))
    except ValueError as e:
        return jsonify(error(400, str(e)))

@thing_controller.route('/<int:id>', methods=['GET'])
def get_thing(id):
    """根据ID查询商品"""
    result = service.get_thing(id)
    if not result:
        return jsonify(error(404, "商品不存在"))
    return jsonify(success(result, "商品查询成功"))

@thing_controller.route('/create', methods=['POST'])
def create_thing():
    """新增商品"""
    data = request.get_json()
    required_fields = ['title', 'price', 'status', 'repertory', 'classification_id']
    for field in required_fields:
        if field not in data:
            return jsonify(error(400, f"缺少必要参数: {field}"))
    try:
        result = service.create_thing(data)
        return jsonify(success(result, "商品新增成功"))
    except ValueError as e:
        return jsonify(error(400, str(e)))

@thing_controller.route('/search', methods=['GET'])
def search_things():
    """根据title模糊查询商品"""
    title = request.args.get('title', '')
    result = service.search_things(title)
    return jsonify(success(result, "商品模糊查询成功"))
@thing_controller.route('/delete/<id>', methods=['DELETE'])
def delete_thing(id):
    """根据ID删除商品"""
    try:
        service.delete_thing(id)
        return jsonify(success(None, "商品删除成功"))
    except BusinessException as e:
        return jsonify(error(e.code, e.message))
    except Exception as e:
        return jsonify(error())